var selectedRow = '', selectedLeftRow = '';
var def_editType = 'add';
var isInit = true;
var isChooseType = false;
var s_pBizName = '';
var defPackageNum = 0, defPackageCount = 1;

$(function () {
    regValidate(["#_bizDataForm"]);
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openInfoChildBizPage();
        },
    }
});

$('#editBizPage').on('hidden.bs.modal', function () {
    resetFormTip('#_bizDataForm');
    resetInputCss('#_bizDataForm');
    defPackageNum = 0;
    defPackageCount = 1;
    $('#_packageInfo').html('');
});

function doRefresh() {
    selectedRow = '';
    var bizName = $('#bizName').val();
    var bizParentCode = '';
    if (!isChooseType) {
        bizParentCode = pBizCode;
    } else {
        if (selectedLeftRow && selectedLeftRow != '') {
            bizParentCode = selectedLeftRow.bizCode;
        }
    }
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'biz/pageFindChildBizData?t=' + new Date().getTime(),
        query: {
            bizName : bizName,
            bizParentCode : bizParentCode
        },
    });
}

function getTypeParams(params) {
    return {
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
}

function getParams(params) {
    var bizName = $('#bizName').val();
    var bizParentCode = '';
    if (!isChooseType) {
        bizParentCode = pBizCode;
    } else {
        if (selectedLeftRow && selectedLeftRow != '') {
            bizParentCode = selectedLeftRow.bizCode;
        }
    }
    return {
        bizName : bizName,
        bizParentCode : bizParentCode,
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
}

function openAddBizPage() {
    if (!isChooseType) {
        if (!pBizCode || pBizCode == '') {
            toastr.error('所选数据存在问题，请刷新页面重试');
            return;
        }
    } else {
        if (!selectedLeftRow || selectedLeftRow == '') {
            toastr.error(common_no_choose_msg.format("添加服务项"));
            return;
        }
    }
    def_editType = 'add';
    $('#_modelTitle').html('新增服务项');
    $('#_parentBiz').html(s_pBizName);
    $('#_bizCode').val('');
    $('#_bizName').val('');
    $('#_sortNum').val('');
    $('#_isRequired').val('Y');
    $('#remark').val('');
    $('#editBizPage').modal('show');
}

function openEditBizPage() {
    def_editType = 'edit';
    if (!selectedRow.id || selectedRow.id == '') {
        toastr.error(common_no_choose_msg.format("编辑"));
        return;
    }
    $('#_modelTitle').html('编辑服务项');
    $('#_parentBiz').html(s_pBizName);
    $('#_bizCode').val(selectedRow.bizCode);
    $('#_bizName').val(selectedRow.bizName);
    $('#_sortNum').val(selectedRow.sortNum);
    $('#_isRequired').val(selectedRow.isRequired);
    $('#remark').val(selectedRow.remark);
    setPackageInfo();
    $('#editBizPage').modal('show');
}

function setPackageInfo() {
    var info = selectedRow.packageInfo;
    if (!info || info == '') {
        return;
    }
    var infoJSON = $.parseJSON(info);
    var htmlStr = '';
    for (var i=0; i<infoJSON.length; i++) {
        var name = infoJSON[i].packageName;
        var code = infoJSON[i].packageCode;
        var str = '<div class="form-group form-group-new" id="div_'+ defPackageCount +'_name">\n' +
            '                            <label class="col-sm-3 control-label">\n' +
            '                                <input type="radio" name="_package" value="'+ defPackageCount +'_name" />\n' +
            '                                <span style="color: red">*</span>服务包名称：\n' +
            '                            </label>\n' +
            '                            <div class="col-sm-7">\n' +
            '                                <input type="text" id="name'+ defPackageCount +'_name" name="packageName" class="form-control" value="'+ name +'" maxlength="20" placeholder="20个字内" required>\n' +
            '                                <input type="hidden" id="code'+ defPackageCount +'_name" name="packageCode" class="form-control" value="'+ code +'">\n' +
            '                                <span class="help-block m-b-none tip"></span>\n' +
            '                            </div>\n' +
            '                        </div>';
        defPackageNum++;
        defPackageCount++;
        htmlStr += str;
    }
    $('#_packageInfo').html(htmlStr);
}

function closeEditBizPage() {
    $('#editBizPage').modal('hide');
    resetFormTip('#_bizDataForm');
    resetInputCss('#_bizDataForm');
    defPackageNum = 0;
    defPackageCount = 1;
    $('#_packageInfo').html('');
}

function openInfoChildBizPage() {
    if (!selectedRow.id || selectedRow.id == '') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $('#lab_parentBiz').html(s_pBizName);
    $('#lab_bizCode').html(selectedRow.bizCode);
    $('#lab_bizName').html(selectedRow.bizName);
    $('#lab_sortNum').html(selectedRow.sortNum);
    $('#lab_remark').html(selectedRow.remark);
    $('#lab_packageNames').html(selectedRow.packageNames);
    if (selectedRow.isRequired == 'Y') {
        $('#lab_isRequired').html('是');
    } else {
        $('#lab_isRequired').html('否');
    }
    $('#bizInfoPage').modal('show');
}

function closeBizInfoPage() {
    $('#bizInfoPage').modal('hide');
    resetFormTip('#_bizDataForm1');
}

function doSaveBiz() {
    if(!$("#_bizDataForm").valid()) return;//校验不通过
    var bizCode = $.trim($('#_bizCode').val());
    var bizName = $.trim($('#_bizName').val());
    var sortNum = $.trim($('#_sortNum').val());
    sortNum = sortNum ? sortNum : 999;
    var isRequired = $('#_isRequired').val();
    var remark = $.trim($('#remark').val());
    var bizParentCode = pBizCode;
    if (isChooseType) {
        bizParentCode = selectedLeftRow.bizCode;
    }
    var postData = {
        bizCode : bizCode,
        bizParentCode : bizParentCode,
        bizName : bizName,
        sortNum : sortNum,
        isRequired : isRequired,
        remark : remark,
    };
    var listData = $('#_packageInfo div div input');
    if (listData && listData.length > 0) {
        var packageList = [];
        var packageNames = [];
        for (var i=0; i<defPackageNum ; i++) {
            var packageInfo = {
                packageName : listData[2*i].value,
                packageCode : listData[2*i+1].value
            };
            packageList.push(packageInfo);
            packageNames.push(listData[2*i].value);
        }
        for (var i=0; i<packageNames.length; i++) {
            for (var j=i+1; j<packageNames.length; j++) {
                if (packageNames[i] == packageNames[j]) {
                    toastr.error('服务包名称不能重复');
                    return;
                }
            }
        }
        postData.packageInfo = packageList;
    }
    var url = basePath + 'biz/addBiz';
    if (def_editType == 'edit') {
        url = basePath + 'biz/editBiz';
        postData.id = selectedRow.id;
    }
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data && data.isSuccess){
                toastr.success(common_save_success);
                closeEditBizPage();
                doRefresh();
            }else if(data&&!data.isSuccess){
                if (data.errorCode == 'EXIST_CODE') {
                    toastr.error('此服务项编码已存在，无法重复添加');
                    return;
                }
                toastr.error(data.errorDesc);
            }else{
                toastr.error(common_save_fail);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function checkBizDelete() {
    if (!selectedRow.id) {
        toastr.error(common_no_choose_msg.format("删除"));
        return;
    }
    var postData = {
        bizCode : selectedRow.bizCode,
    };
    $.ajax({
        type: 'post',
        url: basePath + 'biz/checkBizDelete',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if (!data) {
                toastr.error('校验删除失败');
                return;
            }
            if (!data.isSuccess) {
                if (data.errorCode == 'HAS_REF') {
                    toastr.error('该服务项已关联机构服务，无法删除');
                } else {
                    toastr.error(data.errorDesc);
                    return;
                }
            } else {
                var strHtml = '是否删除服务项【'+selectedRow.bizName+'】？该操作会变更数据！';
                swalToastr('', strHtml, 'warning', deleteBiz);
            }
            return;
        },
    });
}

function deleteBiz() {
    var postData = {
        id : selectedRow.id,
        status : 'delete'
    };
    $.ajax({
        type: 'post',
        url: basePath + 'biz/changeState',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data && data.isSuccess){
                toastr.success('删除成功');
                doRefresh();
            }else if(data&&!data.isSuccess){
                toastr.error(data.errorDesc);
            }else{
                toastr.error('删除失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

//------------------------------------------------------------------------列表数据初始化
function formatIsRequired(value, row, index) {
    if (value == 'Y') {
        return '是';
    }
    if (value == 'N') {
        return '否';
    }
    return value;
}

function initCheck(value, row, index) {
    if (isInit && row.bizCode == pBizCode) {
        setTimeout(function(){
            $("#pDataTable > tbody > tr[data-index='" +index+"']").addClass("success");
        },200);
        isInit = false;
        s_pBizName = value;
    }
    return value;
}

//左边选中事件
$("#pDataTable").on("click-row.bs.table",function(e,row,ele){
    $("#pDataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedLeftRow = row;
    isChooseType = true;
    s_pBizName = row.bizName;
    doRefresh();
});
//右边选中事件
$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRow = row;
});

function doBack() {
    window.location.href = basePath + 'biz/bizPage?searchKey=' + searchKey + '&searchStatus=' + searchStatus +
        '&t=' + new Date().getTime() + '&pageNo=' + searchBizInfo.pageNo + '&pageSize=' + searchBizInfo.pageSize;
}

//---------------------------------------------------------
//增加服务包
function doAddPackage() {
    if (defPackageNum >= 10) {
        toastr.error('最多能添加10个服务包');
        return;
    }
    var str = '<div class="form-group form-group-new" id="div_'+ defPackageCount +'_name">\n' +
        '                            <label class="col-sm-3 control-label">\n' +
        '                                <input type="radio" name="_package" value="'+ defPackageCount +'_name" />\n' +
        '                                <span style="color: red">*</span>服务包名称：\n' +
        '                            </label>\n' +
        '                            <div class="col-sm-7">\n' +
        '                                <input type="text" id="name'+ defPackageCount +'_name" name="packageName" class="form-control" maxlength="20" placeholder="20个字内" required>\n' +
        '                                <input type="hidden" id="code'+ defPackageCount +'_name" name="packageCode" class="form-control">\n' +
        '                                <span class="help-block m-b-none tip"></span>\n' +
        '                            </div>\n' +
        '                        </div>';
    $('#_packageInfo').append(str);
    defPackageCount++;
    defPackageNum++;
}

//删除服务包
function doDelPackage() {
    var val =$('input[name="_package"]:checked').val();
    if (!val || val == '') {
        toastr.error('请先选中一个服务包再删除');
        return;
    }
    var codeId = 'code' + val;
    var packageCode = $('#' + codeId).val();
    var postData = {
        packageCode : packageCode
    }
    $.ajax({
        type: 'post',
            url: basePath + 'biz/checkPackageExist',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data && data.isSuccess) {
                var strHtml = '确认删除服务包吗？';
                swalToastr('', strHtml, 'warning', delPackage);
            }else if(data&&!data.isSuccess){
                if (data.errorCode == 'EXIST_CODE') {
                    toastr.error('此服务包已关联服务，无法删除');
                    return;
                }
                toastr.error(data.errorDesc);
            }else{
                toastr.error('删除失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function delPackage() {
    var val =$('input[name="_package"]:checked').val();
    var packageName = $('#name' + val).val();
    if (!val || val == '') {
        return;
    }
    var id2 = 'div_' + val;
    $('#'+ id2).remove();
    defPackageNum--;
    toastr.success('成功删除'+ packageName + '服务包');
}
